#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   run.py
@Time    :   2020/09/29 10:44:05
@Author  :   fengzhilaoling
@Version :   1.0
@Contact :   fengzhilaoling@163.com
'''
from flask import Flask
from flask import request
from flask import jsonify
from flask_mail import Mail, Message
from threading import Thread
from datetime import datetime
from random import randrange


class config:
    MAIL_SERVER = 'smtp.126.com'  # 发送邮件服务器
    MAIL_PORT = 25  # 邮件服务器端口
    MAIL_USE_TLS = True
    MAIL_USERNAME = 'fengzhilaoling@126.com'  # 发件人邮箱
    MAIL_PASSWORD = 'JEGFEUTPRVEPCJLZ'  # 授权码
    FLASK_MAIL_SUBJECT_PREFIX = '[XXX平台]'  # 邮件标题
    DEBUG = True


app = Flask(__name__)
app.config.from_object(config)
email = Mail(app)


# 发送邮件
def send_async_mail(app, msg):
    # 确认程序上下文被激活
    with app.app_context():
        email.send(msg)


def send_email(to, mail_code):
    """
    :param to-->收件人
    :param mail_code-->验证码
    """
    msg = Message(app.config['FLASK_MAIL_SUBJECT_PREFIX'] + '您的注册验证码：', \
        sender=app.config['MAIL_USERNAME'], recipients=[to])
    
    msg.body = 'email'
    msg.html = f'''
    <h1>
        亲爱的,
    </h1>
    <h3>
        欢迎来到 <b>XXX平台</b>!
    </h3>
    <p>
        您的验证码为 &nbsp;&nbsp; <b>{mail_code}</b> &nbsp;&nbsp; 赶快去完善注册信息吧！！！
    </p>

    <p>感谢您的支持和理解</p>
    <p>来自：XXX平台</p>
    <p><small>{datetime.utcnow}</small></p>
    '''
    thread = Thread(target=send_async_mail, args=(app, msg))
    thread.start()
    return thread


@app.route('/login/', methods=['POST'])
def login():
    user_name = request.json.get('username')
    email = request.json.get('email')
    print(user_name)
    print(email)
    print('*'*20)
    if user_name == 'fengling':
        mail_code = randrange(1000,9999)
        # 使用redis进行存储，user_name为key，验证码为value
        # redis存储成功通过邮箱发送验证码

        send_email(to=email, mail_code=str(mail_code))
        data = {
            'code': 0,
            'msg': 'email send success'
        }
        return jsonify(data)
    else:
        return jsonify({'msg': 'fail'})

if __name__ == "__main__":
    app.run()
